package com.acme.bankapp.service.bank.listener.email;

import java.util.LinkedList;
import java.util.List;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class BankBlockingQueue<T> {
    private final int maxQueueSize;
    private final List<T> queue = new LinkedList<>();
    private volatile boolean isClosed;

    public BankBlockingQueue(int maxQueueSize) {
        this.maxQueueSize = maxQueueSize;
    }

    public synchronized void close() {
        isClosed = true;
    }

    public synchronized void add(T elem) throws InterruptedException, IllegalStateException {
        if (isClosed) {
            throw new IllegalStateException("Queue is closed. Can't add Element.");
        } else {
            while (queue.size() == maxQueueSize) {
                wait();
            }
            queue.add(elem);
            notifyAll();
        }
    }

    public synchronized T get() throws InterruptedException {
        while (queue.isEmpty()) {
            wait();
        }
        T result = queue.remove(0);
        notifyAll();
        return result;
    }

    public synchronized T compareAndGet() {
        if (queue.isEmpty()) {
            return null;
        } else {
            T result = queue.remove(0);
            notifyAll();
            return result;
        }
    }
}
